package com.ahy231.service.impl;

import com.ahy231.dto.TruckInfo;
import com.ahy231.entity.UserTruck;
import com.ahy231.mapper.UserTruckMapper;
import com.ahy231.service.*;
import com.ahy231.utils.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.*;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author ahy231
 * @date 2021/8/2 16:12
 * @description
 */
@Service
public class TruckServiceImpl implements TruckService {

    private final UserTruckMapper userTruckMapper;

    public TruckServiceImpl(UserTruckMapper userTruckMapper) {
        this.userTruckMapper = userTruckMapper;
    }

    @Override
    public Boolean addTruck(TruckInfo truck) {
        Long userId = getUserId();
        Assert.notNull(userId, "service 获取不到用户 id");
        return userTruckMapper.insert(new UserTruck(null, userId, truck.getName(), truck.getType(), truck.getWeight(), truck.getStatus())) == 1;
    }

    @Override
    public List<TruckInfo> getTrucks() {
        Long userId = getUserId();
        Assert.notNull(userId, "service 获取不到用户 id");
        List<UserTruck> trucks = userTruckMapper.selectList(new QueryWrapper<UserTruck>().eq("user_id", userId));
        return trucks.stream().map(userTruck ->
                new TruckInfo(Long.toString(userTruck.getId()), userTruck.getName(), userTruck.getType(), userTruck.getWeight(), userTruck.getStatus()))
                .collect(Collectors.toList());
    }

    @Override
    public Boolean removeTruck(Long truckId) {
        return userTruckMapper.deleteById(truckId) > 0;
    }

    @Override
    public Boolean setStatus(Long truckId, Integer status) {
        Long userId = getUserId();
        Assert.notNull(userId, "service 获取不到用户 id");

        Assert.isTrue(userTruckMapper.selectCount(new QueryWrapper<UserTruck>().eq("user_id", userId).eq("id", truckId)) > 0, "该车辆不属于该用户");

        Assert.isTrue(userTruckMapper.updateById(UserTruck.builder()
                .id(truckId)
                .status(status)
                .build()) > 0, "更新状态失败");

        return true;
    }

    private Long getUserId() {
        return JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
    }
}
